package com.rightsidetech.http.controller.admin.system;

import com.aliyun.oss.OSS;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.PageRequest;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.config.AliyunOSSConfig;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.enums.ModifyName;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.commom.utils.MD5Files;
import com.rightsidetech.commom.utils.UplodeUtils;
import com.rightsidetech.http.aspect.Auth;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.ModifyLog;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.system.dtos.request.AppInsertReq;
import com.rightsidetech.system.dtos.request.AppUpdateReq;
import com.rightsidetech.system.dtos.response.FileDateResp;
import com.rightsidetech.system.dtos.response.SysAppVersionResp;
import com.rightsidetech.system.service.AppUpdateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.math.BigDecimal;

/**
 * @author yhr
 */
@RestController
@RequestMapping("/admin/appUpdate")
@ShenyuSpringMvcClient(path = "/admin/appUpdate/**")
@Api(tags = "admin:app版本升级相关")
public class AppUpdateController extends BaseController {

    @Resource
    private OSS ossClient;

    @Resource
    private AliyunOSSConfig aliyunOSSConfig;

    @Resource
    private AppUpdateService appUpdateService;

    // 允许上传的格式 安卓/ios软件
    private static final String[] APP_TYPE = new String[]{".apk", ".ipa"};
    //app大小限制100M
    private static final BigDecimal MAX_APP_SIZE = new BigDecimal(102400);

    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @GetMapping("/versionPage")
    @ApiOperation(value = "列表分页")
    public ResponseData<PageInfo<SysAppVersionResp>> versionPage(PageRequest req) {
        return appUpdateService.versionPage(req);
    }

    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @PostMapping("/insertVersion")
    @ApiOperation(value = "添加app版本")
    @ModifyLog(serviceClass = AppUpdateService.class,modifyType = ModifyName.SAVE)
    public ResponseData insertVersion(@RequestBody AppInsertReq updateReq) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(updateReq);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        return appUpdateService.insertAppDate(updateReq, loginInfoId, "insert");
    }

    @Log
    @Token
    @Auth(bizType = Auth.OPERATOR)
    @PostMapping("/updateVersion")
    @ApiOperation(value = "更新app版本")
    @ModifyLog(serviceClass = AppUpdateService.class)
    public ResponseData updateVersion(@RequestBody AppUpdateReq updateReq) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(updateReq);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        return appUpdateService.insertAppDate(updateReq, loginInfoId, "update");
    }

    @Log
    @Token
    @PostMapping("/app_uplode")
    @ApiOperation("app上传")
    @Auth(bizType = Auth.OPERATOR)
    public ResponseData<FileDateResp> moreUplode(MultipartFile file) throws Exception {
        boolean isLegal = false;
        FileDateResp resp = new FileDateResp();
        if (null == file) {
            return ResponseData.fail("文件不能为空");
        }
        for (String type:APP_TYPE) {
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)){
                isLegal = true;
            }
        }
        BigDecimal fileSize =  UplodeUtils.getFileSize(file).multiply(new BigDecimal(1024));
        if (fileSize.compareTo(BigDecimal.ZERO) <= 0) {
            return ResponseData.fail(file.getOriginalFilename() + "文件不合法");
        }
        if (fileSize.compareTo(MAX_APP_SIZE) > 0) {
            return ResponseData.fail("文件大小不能大于" + MAX_APP_SIZE + "M");
        }
        if (isLegal){
            ResponseData<String> upload = UplodeUtils.upload(file, ossClient, aliyunOSSConfig);
            resp.setUrl(upload.getResData());
            resp.setMd5(MD5Files.getFileMD5(file));
        }else {
            return ResponseData.fail("文件格式错误");
        }
        return ResponseData.success(resp);
    }


}
